﻿using System;

namespace Common.Utility
{
    /// <summary>
    /// 时间操作辅助管理类
    /// </summary>
    public class DateTimeHelper
    {
        /// <summary>
        /// 将时间转换为对应的UNIX时间戳
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static long ToUnixTime(DateTime datetime)
        {
            TimeSpan span = (datetime - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            return (long)span.TotalSeconds;
        }

        /// <summary>
        /// 将时间转换为对应的UNIX时间戳(毫秒)
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static long ToUnixTimeMs(DateTime datetime)
        {
            TimeSpan span = (datetime - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            return (long)span.Milliseconds;
        }

        /// <summary>
        /// 将Unix时间戳转换为时间
        /// </summary>
        /// <param name="unixTime"></param>
        /// <returns></returns>
        public static DateTime FromUnixTime(double unixTime)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime().AddSeconds(unixTime);
        }

        /// <summary>
        ///  将Unix时间戳转换为时间
        /// </summary>
        /// <param name="msSince1970"></param>
        /// <returns></returns>
        public static DateTime FromUnixTimeMs(double msSince1970)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime().AddMilliseconds(msSince1970);
        }
    }
}
